package com.ruoyi.wvp.api.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DeletedEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wvp.api.ApiAjaxResult;
import com.ruoyi.wvp.api.entity.ImageDTO;
import com.ruoyi.wvp.api.entity.SurveillanceDTO;
import com.ruoyi.wvp.config.MonitorPlatformConfig;
import com.ruoyi.wvp.domain.ImageEvent;
import com.ruoyi.wvp.domain.Surveillance;
import com.ruoyi.wvp.domain.SurveillanceEvent;
import com.ruoyi.wvp.sdk.monitor.IMonitorSdkService;
import com.ruoyi.wvp.sdk.monitor.entity.MonitorEventInfo;
import com.ruoyi.wvp.sdk.monitor.entity.PageEntity;
import com.ruoyi.wvp.sdk.monitor.entity.params.AlarmEventPageParams;
import com.ruoyi.wvp.service.IImageEventService;
import com.ruoyi.wvp.service.ISurveillanceEventService;
import com.ruoyi.wvp.service.ISurveillanceService;
import com.ruoyi.wvp.utils.DateUtil;
import com.ruoyi.wvp.utils.JwtUtil;
import com.ruoyi.wvp.utils.UnicodeConverterUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 蒋翔 SY100242
 * @date 2024/7/22 9:33
 * @email SY100242@hnlens.com
 */
@RestController
@Slf4j
@RequestMapping("/wvp/v1/api/surveillance")
@Tag(name = "API 回调管理")
public class ApiSurveillanceOutController {

    @Autowired
    private ISurveillanceEventService surveillanceEventService;
    @Autowired
    private ISurveillanceService surveillanceService;
    @Autowired
    private IImageEventService imageEventService;

    @PostMapping("/add/{channelId}")
    @Anonymous
    @Operation(summary = "实时监控回调")
    public ApiAjaxResult addSurveillance(@RequestBody SurveillanceDTO dto, HttpServletRequest request, @PathVariable String channelId) {
        log.info(dto.toString());
        String token = JwtUtil.getToken(request);
        try {
            Claims claims = JwtUtil.parseToken(token, "3ddc30c87007583a96ae5bc6376b8a5b");
            SurveillanceEvent event = new SurveillanceEvent();
            if (StringUtils.isNotBlank(dto.getIntelligentTypeStr())) {
                event.setEventTypeStr(UnicodeConverterUtil.unicodeToString(dto.getIntelligentTypeStr()));
            }
            if(StringUtils.isBlank(event.getEventTypeStr())){
                return ApiAjaxResult.error("没有事件类型不保存", true);
            }
            String monitorCodeStr = dto.getMonitorCode();
            if (StringUtils.isNotBlank(monitorCodeStr)) {
                String[] split = monitorCodeStr.split("#");
                if (split.length < 1) {
                    return ApiAjaxResult.error("找不到当前设备", false);
                }
                String monitorCode = split[0];
                Surveillance surveillance = surveillanceService.getByMonitorCode(monitorCode);
                if (surveillance == null) {
                    return ApiAjaxResult.error("找不到当前设备", false);
                }
                event.setDeviceNumber(surveillance.getDeviceNumber());
                event.setDeviceBrand(surveillance.getDeviceBrand());
                event.setDeviceModel(surveillance.getDeviceModel());
                event.setSurveillanceId(surveillance.getId());
                event.setCityCode(surveillance.getCityCode());
                event.setCityName(surveillance.getCityName());
                event.setStreetCode(surveillance.getStreetCode());
                event.setStreetName(surveillance.getStreetName());
                event.setAreaCode(surveillance.getAreaCode());
                event.setAreaName(surveillance.getAreaName());
                event.setDeviceName(surveillance.getDeviceName());
                if (StringUtils.isNotBlank(surveillance.getCommunity())) {
                    event.setCommunity(surveillance.getCommunity());
                }
                if(StringUtils.isNotBlank(surveillance.getCommunityCode())){
                    event.setCommunityCode(surveillance.getCommunityCode());
                }
                if (StringUtils.isNotBlank(surveillance.getResidentialName())) {
                    event.setResidentialName(surveillance.getResidentialName());
                }
                if(StringUtils.isNotBlank(surveillance.getResidentialCode())) {
                    event.setResidentialCode(surveillance.getResidentialCode());
                }
                if (StringUtils.isNotBlank(surveillance.getAddress())) {
                    event.setAddress(surveillance.getAddress());
                }
                if (StringUtils.isNotBlank(surveillance.getSerialNumber())) {
                    event.setSerialNumber(surveillance.getSerialNumber());
                }

            }
            if (StringUtils.isNotBlank(dto.getEventCode())) {
                event.setEventCode(dto.getEventCode());
            }
            if (StringUtils.isNotBlank(dto.getPicUrl())) {
                event.setPicUrl(dto.getPicUrl());
            }
            if (Objects.nonNull(dto.getLatestTimeStr())) {
                event.setEventBeginTime(dto.getLatestTimeStr());
            }
            if (StringUtils.isNotBlank(dto.getDurationTimeStr())) {
                event.setEventDurationTime(UnicodeConverterUtil.unicodeToString(dto.getDurationTimeStr()));
            }
            event.setCreateBy("事件推送");
            event.setCreateTime(new Date());
            if (Objects.nonNull(dto.getImgWidth())) {
                event.setImgWidth(dto.getImgWidth());
            }
            if (Objects.nonNull(dto.getImgHeight())) {
                event.setImageHeight(dto.getImgHeight());
            }
            if (Objects.nonNull(dto.getViolationAreas())) {
                try {
                    event.setImgLocation(JSON.toJSONString(dto.getViolationAreas()));
                } catch (Exception e) {
                    log.error("转换错误", e);
                }
            }
//            boolean save = surveillanceEventService.save(event);
            boolean save = surveillanceEventService.addSurveillanceEvent(event);
            return ApiAjaxResult.success(save);
        } catch (Exception e) {
            if (e.getClass().equals(DuplicateKeyException.class)) {
                return ApiAjaxResult.error("数据已存在", true);
            }
            log.error(e.toString());
        }
        log.info("surveillance event:{}", dto);
        return ApiAjaxResult.error("登录验证失败", false);
    }

    @PostMapping("/image/{channelId}")
    @Anonymous
    @Operation(summary = "督导员图片回调")
    public ApiAjaxResult image(@RequestBody ImageDTO dto, HttpServletRequest request, @PathVariable String channelId){
        log.info(dto.toString());
        String token = JwtUtil.getToken(request);
        try {
            Claims claims = JwtUtil.parseToken(token, "3ddc30c87007583a96ae5bc6376b8a5b");
            if(StringUtils.isBlank(dto.getPicUrl())){
                return ApiAjaxResult.error("请传递图片:picUrl",false);
            }
            ImageEvent imageEvent = new ImageEvent();
            imageEvent.setPicUrl(dto.getPicUrl());
            imageEvent.setCreateBy("系统");
            Date createTime = new Date();
            imageEvent.setCreateTime(createTime);
            imageEvent.setUpdateBy("系统");
            imageEvent.setUpdateTime(createTime);
            imageEvent.setDeleted(DeletedEnum.NOMAL.getValue());
            imageEvent.setCreateDate(getCreateDate(dto.getPicUrl()));
            imageEventService.save(imageEvent);
            return ApiAjaxResult.success(true);
        }catch (Exception e) {
            if (e.getClass().equals(DuplicateKeyException.class)) {
                return ApiAjaxResult.error("数据已存在", true);
            }
            log.error(e.toString());
        }
        log.info("surveillance image:{}", dto);
        return ApiAjaxResult.error("登录验证失败", false);

    }

    private LocalDate getCreateDate(String picUrl) {
        try {
            String[] split = picUrl.split("/")[6].split("_");
            return LocalDateTime.ofEpochSecond(Long.parseLong(split[1]),0, ZoneOffset.UTC).toLocalDate();
        } catch (NumberFormatException e) {
            log.error("转换错误",e);
        }
        return LocalDate.now();
    }


//
//    @GetMapping("/test")
//    @Anonymous
//    @Operation(summary = "测试")
//    public AjaxResult test() {
//
//        AlarmEventPageParams alamEventPageParams = new AlarmEventPageParams();
//        alamEventPageParams.setPageNo(1);
//        alamEventPageParams.setPageSize(100);
//        alamEventPageParams.setProjectId(monitorPlatformConfig.getProjectId());
//        alamEventPageParams.setMonitorCode(List.of("AA5117614#1"));
//        LocalDateTime date = LocalDateTime.now();
//        LocalDateTime beginTime = date.with(TemporalAdjusters.firstDayOfMonth());
//        alamEventPageParams.setBeginTime(DateUtil.getDateTimeStrEt(beginTime));
//        alamEventPageParams.setEndTime(DateUtil.getDateTimeStrEt(date));
//        PageEntity<MonitorEventInfo> monitorInfo = monitorSdkService.getEventList(alamEventPageParams);
//        List<MonitorEventInfo> list = monitorInfo.getList();
//        ArrayList<SurveillanceEvent> surveillanceEvents = new ArrayList<>(list.size());
//        list.forEach(item -> {
//            SurveillanceEvent surveillanceEvent = new SurveillanceEvent();
//            surveillanceEvent.setEventCode(item.getEventCode());
//            surveillanceEvent.setEventType(item.getOriginalType());
//            surveillanceEvent.setPicUrl(item.getPicUrl());
//            surveillanceEvent.setEventBeginTime(item.getCollectTimeStr());
//            surveillanceEvent.setImageHeight(Long.valueOf(item.getImgHeight()));
//            surveillanceEvent.setImgWidth(Long.valueOf(item.getImgWidth()));
//            surveillanceEvent.setImgLocation(item.getViolationAreas());
//            surveillanceEvent.setCreateBy("事件回调");
//            surveillanceEvent.setCreateTime(new Date());
//            surveillanceEvent.setEventTypeStr(item.getIntelligentTypeStr());
//            surveillanceEvent.setSurveillanceId(1815565136793780226L);
//            surveillanceEvents.add(surveillanceEvent);
//        });
//        surveillanceEventService.saveBatch(surveillanceEvents);
//        return AjaxResult.success(monitorInfo);
////        LiveParams params=new LiveParams();
////        params.setProjectId(monitorPlatformConfig.getProjectId());
////        params.setExpireTime(0L);
////        params.setMonitorCode("AA5117614#1");
////        LiveInfo liveInfo = monitorSdkService.getLiveInfo(params);
////        LiveHistoryParams params=new LiveHistoryParams();
////        params.setDeviceSerial("AA5117614#1");
////        params.setType(2);
////        params.setProtocol(4);
////        LocalDate localDate = LocalDate.now().minusDays(1L);
////        LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.of(0, 0, 0));
////        String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
////        params.setStartTime(format);
////        LiveHistoryInfo liveHistoryInfo = monitorSdkService.getLiveHistoryInfo(params);
////        return AjaxResult.success(liveHistoryInfo);
//    }
}
